/*
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * The Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 *
 * The Initial Developer of the Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 * Portions created by Mark A. Kobold are Copyright (C) 2000-2007. All Rights Reserved.
 *
 * Contributor(s): 
 *  Mark A. Kobold [mkobold <at> isqlviewer <dot> com].
 *  
 * If you didn't download this code from the following link, you should check
 * if you aren't using an obsolete version: http://www.isqlviewer.com
 */
package org.isqlviewer.ui.wizards.service;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.sql.SQLException;
import java.util.Date;

import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.text.Document;

import org.isqlviewer.ServiceReference;
import org.isqlviewer.sql.JdbcService;
import org.isqlviewer.sql.embedded.EmbeddedDatabase;
import org.isqlviewer.swing.SwingUtilities;
import org.isqlviewer.swing.action.SharedActions;
import org.isqlviewer.swing.action.SwingEventManager;
import org.isqlviewer.ui.wizards.AbstractWizardStep;
import org.isqlviewer.ui.wizards.WizardContext;
import org.isqlviewer.util.BasicUtilities;
import org.isqlviewer.util.IsqlToolkit;
import org.isqlviewer.util.LocalMessages;
import org.isqlviewer.xml.ServiceDigester;

public class ConfirmNewService extends AbstractWizardStep implements ActionListener {

    private LocalMessages messages = new LocalMessages(ServiceWizard.BUNDLE_NAME);
    private Document nameDocument = null;
    private Document urlDocument = null;
    private Document classDocument = null;
    private ButtonGroup versionCompatability = new ButtonGroup();
    private JCheckBox connectOnFinish = null;

    public void actionPerformed(ActionEvent event) {

    }

    public boolean isFirst() {

        return false;
    }

    public boolean isLast() {

        return true;
    }

    public boolean isValid(WizardContext context) {

        JdbcService service = (JdbcService) context.getAttribute(ServiceWizard.ATTRIBUTE_SERVICE);
        String stringVersion = versionCompatability.getSelection().getActionCommand();
        int version = Integer.parseInt(stringVersion);

        String safeName = BasicUtilities.createSafeFilename(service.getName());
        File file = new File(IsqlToolkit.getBaseDirectory(), safeName + ".service");
        FileOutputStream outputStream;
        try {
            outputStream = new FileOutputStream(file, false);
            context.info("saving service:" + service.getName() + " to location:" + file.getAbsolutePath());
            ServiceDigester.writeService(version, outputStream, service);
        } catch (FileNotFoundException e) {

        }

        EmbeddedDatabase database = EmbeddedDatabase.getSharedInstance();
        ServiceReference serviceReference = new ServiceReference();
        serviceReference.setName(service.getName());
        serviceReference.setOrder(0);
        try {
            serviceReference.setResourceURL(file.toURL());
        } catch (MalformedURLException error) {
        }

        SwingEventManager eventManager = context.getEventManager();
        if (connectOnFinish.isSelected()) {
            serviceReference.setLastUsed(new Date());
            context.info("Connnecting to new service:" + service.getName());
            eventManager.actionPerformed(new ActionEvent(this, SharedActions.SERVICE_CONNECT, service.getName()));
        }

        try {
            database.addService(serviceReference);
            eventManager.actionPerformed(new ActionEvent(this, SharedActions.SERVICE_ADDED, service.getName()));
        } catch (SQLException sqle) {
            error("", sqle);
        }

        return true;
    }

    @Override
    public void activate(WizardContext context) {

        JdbcService service = (JdbcService) context.getAttribute(ServiceWizard.ATTRIBUTE_SERVICE);
        if (service != null) {
            SwingUtilities.replaceDocumentContent(nameDocument, service.getName());
            SwingUtilities.replaceDocumentContent(urlDocument, service.getUrl());
            SwingUtilities.replaceDocumentContent(classDocument, service.getDriverClass());
        }
    }

    @Override
    public void init(WizardContext context) {

        setTitle(messages.getMessage("newservicewizard.finalize-service.title"));
        setComment(messages.getMessage("newservicewizard.finalize-service.tip"));
        setImage(SwingUtilities.loadIconResource(ServiceWizard.class, "ok", 22));

        JPanel panel = new JPanel(new GridBagLayout());
        setView(panel);

        Object constraint = null;
        JComponent component = null;
        JLabel label = null;
        String title = null;
        String tip = null;

        title = messages.format("newservicewizard.servicename.title");
        tip = messages.format("newservicewizard.servicename.tip");
        component = new JTextField(32);
        component.setToolTipText(tip);
        component.setFont(component.getFont().deriveFont(Font.BOLD));
        ((JTextField) component).setEditable(false);
        nameDocument = ((JTextField) component).getDocument();
        constraint = ServiceWizard.constrain(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE);
        label = new JLabel(title);
        label.setLabelFor(component);
        panel.add(label, constraint);
        constraint = ServiceWizard.constrain(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);
        panel.add(component, constraint);

        title = messages.format("newservicewizard.jdbcdriver.title");
        tip = messages.format("newservicewizard.jdbcdriver.tip");
        component = new JTextField(32);
        component.setToolTipText(tip);
        component.setFont(component.getFont().deriveFont(Font.BOLD));
        ((JTextField) component).setEditable(false);
        classDocument = ((JTextField) component).getDocument();
        constraint = ServiceWizard.constrain(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE);
        label = new JLabel(title);
        label.setLabelFor(component);
        panel.add(label, constraint);
        constraint = ServiceWizard.constrain(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);
        panel.add(component, constraint);

        title = messages.format("newservicewizard.jdbcurl.title");
        tip = messages.format("newservicewizard.jdbcurl.tip");
        component = new JTextField(32);
        component.setToolTipText(tip);
        component.setFont(component.getFont().deriveFont(Font.BOLD));
        ((JTextField) component).setEditable(false);
        urlDocument = ((JTextField) component).getDocument();
        constraint = ServiceWizard.constrain(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE);
        label = new JLabel(title);
        label.setLabelFor(component);
        panel.add(label, constraint);
        constraint = ServiceWizard.constrain(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);
        panel.add(component, constraint);

        constraint = ServiceWizard.constrain(0, 3, 2, 1, 1.0d, 0.0d, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);
        panel.add(new JSeparator(SwingConstants.HORIZONTAL), constraint);
        panel.add(Box.createVerticalStrut(32), constraint);

        title = messages.format("newservicewizard.compatability_info");
        component = new JLabel(title);
        constraint = ServiceWizard.constrain(0, 4, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE);
        panel.add(component, constraint);

        title = messages.format("newservicewizard.compatability");
        tip = messages.format("newservicewizard.compatability.tip");
        component = new JRadioButton();
        versionCompatability.add((JRadioButton) component);
        ((JRadioButton) component).setText(title);
        ((JRadioButton) component).setSelected(true);
        ((JRadioButton) component).setActionCommand(Integer.toString(ServiceDigester.VERSION_2));
        component.setToolTipText(tip);
        constraint = ServiceWizard.constrain(0, 5, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE);
        panel.add(component, constraint);

        title = messages.format("newservicewizard.no-compatability");
        tip = messages.format("newservicewizard.no-compatability.tip");
        component = new JRadioButton();
        versionCompatability.add((JRadioButton) component);
        ((JRadioButton) component).setText(title);
        ((JRadioButton) component).setActionCommand(Integer.toString(ServiceDigester.VERSION_3));
        component.setToolTipText(tip);
        constraint = ServiceWizard.constrain(0, 6, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE);
        panel.add(component, constraint);

        title = messages.format("newservicewizard.connect_on_finish");
        tip = messages.format("newservicewizard.connect_on_finish.tip");
        connectOnFinish = new JCheckBox(title);
        connectOnFinish.setToolTipText(tip);
        connectOnFinish.setSelected(true);
        constraint = ServiceWizard.constrain(0, 7, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST,
                GridBagConstraints.NONE);
        panel.add(connectOnFinish, constraint);

        component = (JComponent) Box.createVerticalGlue();
        component.setName("GLUE");
        component.setToolTipText(tip);
        constraint = ServiceWizard.constrain(0, 7, 2, 1, 0.0, 1.0, GridBagConstraints.CENTER,
                GridBagConstraints.VERTICAL);
        panel.add(component, constraint);
    }
}